package com.haihui.platform.controller.sys;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.haihui.platform.controller.BaseController;
import com.haihui.platform.entity.SysAdUserInfo;
import com.haihui.platform.service.roles.ResourceService;

/*
 * 首页的接口
 */
@Controller
@RequestMapping("/index")
public class IndexController extends BaseController{

	private static final Logger LOG = Logger.getLogger(IndexController.class);
	
	@Autowired
	private ResourceService resourceService;
	
	/**
	 * 左侧菜单
	 */
	@RequestMapping(value="/menu")
	public void menu(HttpServletRequest request){
		try{
			SysAdUserInfo user = (SysAdUserInfo)request.getSession().getAttribute("user");
			List<Map<String, Object>> list = resourceService.getResourceByUser(user.getAduserId());
			List<Map<String, Object>> reslist = new ArrayList<Map<String, Object>>();
			loop(list,reslist,null);
			this.responseWriter(this.getCommonJsonString(true, "查询成功", reslist));
		}catch(Exception e){
			LOG.error(e.getMessage(),e);
			this.responseWriter(this.getCommonJsonString(false, "查询失败"));
		}
	}
	
	//循环资源列表
	@SuppressWarnings("unchecked")
	private void loop(List<Map<String, Object>> list, List<Map<String, Object>> reslist, Map<String, Object> map){
		if(map != null){
			for(Map<String, Object> m : list){
				if(m.get("parentId") != null && m.get("parentId").equals(map.get("resId"))){
					loop(list,reslist,m);
					if(map.get("childs") != null){
						((List<Map<String, Object>>)map.get("childs")).add(m);
					}else{
						List<Map<String, Object>> ll = new ArrayList<Map<String, Object>>();
						ll.add(m);
						map.put("childs", ll);
					}
				}
			}
		}else{
			for(Map<String, Object> m : list){
				if(m.get("parentId") == null){
					loop(list,reslist,m);
					reslist.add(m);
				}
			}
		}
	}
	
}
